#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author  : lkm

"""
    BP神经网络模型，可直接调用
    数据格式如司马奎《数学建模算法与应用》中的案例数据 jingliu.txt，导入方式：

data = pd.read_csv(r"jingliu.txt", names=['x1','x2','x3','x4','y'], sep='\t', encoding='utf-8').values
x, y = data[:, :4], data[:, 4]

"""

import warnings
import pandas as pd
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import cross_val_score, KFold

warnings.filterwarnings('ignore')

""" 模型建立 """
def Model(x, y):
    model = MLPRegressor().fit(x, y)
    return model

""" 预测：回归 """
def Model_Predict(x0, BP_model):
    y0 = BP_model.predict(x0)
    return y0

""" 检验：平均绝对误差(sklean方法) """
def MAE(BP_model, x, y):
    kfold = KFold(n_splits=10, random_state=7, shuffle=True)
    mae = cross_val_score(BP_model, x, y, cv=kfold, scoring='neg_mean_absolute_error')
    mae_mean, mae_std = mae.mean(), mae.std()
    return mae_mean, mae_std

""" 检验：平均误差(mean_error) """
def Mean_Error(x, y, BP_model):
    y0 = BP_model.predict(x)
    mean_error = (y0 - y).mean()
    return mean_error

""" 相关参数 """
def Relevent_Parameters(BP_model):
    loss = BP_model.loss_ # 损失函数计算出的当前损失值
    coefs = BP_model.coefs_ # 列表中的第i个元素表示i层的权重矩阵
    intercepts = BP_model.intercepts_ # 列表中第i个元素表示i+1层的偏差向量
    n_iter = BP_model.n_iter_ # 迭代次数
    n_layers = BP_model.n_layers_ # 层数
    n_outputs = BP_model.n_outputs_ # 输出的个数
    out_activation = BP_model.out_activation_ # 输出激活函数的名称
    return loss, coefs, intercepts, n_iter, n_layers, n_outputs, out_activation